package com.lanren.familybookapp.ui.home.view;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.hjq.toast.ToastUtils;
import com.lanren.common.utils.DocumentsUtils;
import com.lanren.common.utils.FileUtils;
import com.lanren.common.utils.LogUtils;
import com.lanren.common.utils.StringUtils;
import com.lanren.common.utils.Utils;
import com.lanren.common.utils.event.C;
import com.lanren.common.widget.SwitchMultiButton;
import com.lanren.common.widget.TitleBarView;
import com.lanren.common.widget.statusbar.ImmersionBar;
import com.lanren.easyeventbus.Event;
import com.lanren.easyeventbus.EventBusUtil;
import com.lanren.easyhttp.body.UIProgressResponseCallBack;
import com.lanren.easyhttp.subsciber.IProgressDialog;
import com.lanren.familybookapp.R;
import com.lanren.familybookapp.app.AppUserHelper;
import com.lanren.familybookapp.base.BaseUiActivity;
import com.lanren.familybookapp.ui.home.interfaces.ICSVImportModel;
import com.lanren.familybookapp.ui.home.model.CSVImportModel;
import com.lanren.familybookapp.ui.home.presenter.CSVImportPresenter;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @ClassName CSVImportActivity
 * @Description TODO
 * @Author chongheng.wang
 * @Date 2020/2/13 17:31
 * @Version 1.0
 */
public class CSVImportActivity extends BaseUiActivity<CSVImportPresenter> implements ICSVImportModel.ICSVImportView {


    @BindView(R.id.title_view)
    TitleBarView titleView;
    @BindView(R.id.content_txt)
    TextView contentTxt;
    @BindView(R.id.book_import)
    Button bookImport;
    @BindView(R.id.book_csv_path)
    TextView bookCsvPath;
    @BindView(R.id.book_csv_add)
    TextView bookCsvAdd;
    @BindView(R.id.book_ali_wechat)
    SwitchMultiButton bookAliWechat;

    private int bookType = 1;
    private File fileCSV;
    public static final int OPEN_DOCUMENT_FILE_CODE = 100;

    private File fileSave = null;
    private String newPath = null;

    private ProgressDialog dialog;
    private IProgressDialog mProgressDialog = new IProgressDialog() {
        @Override
        public Dialog getDialog() {
            if (dialog == null) {
                dialog = new ProgressDialog(CSVImportActivity.this);
                dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置进度条的形式为圆形转动的进度条
                dialog.setMessage("正在上传...");
                // 设置提示的title的图标，默认是没有的，如果没有设置title的话只设置Icon是不会显示图标的
                dialog.setTitle("文件上传");
                dialog.setMax(100);
            }
            return dialog;
        }
    };

    final UIProgressResponseCallBack listener = new UIProgressResponseCallBack() {
        @Override
        public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
            int progress = (int) (bytesRead * 100 / contentLength);
            LogUtils.d(progress + "%");
            dialog.setProgress(progress);
            dialog.setMessage(progress + "%");
            if (done) {//完成
                dialog.setMessage("文件上传完成，正在解析中....");
            }
        }
    };

    @Override
    public CSVImportPresenter createPresenter() {
        return new CSVImportPresenter(new CSVImportModel());
    }

    @Override
    protected void setStatusBar() {
        mImmersionBar = ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_csv_import;
    }

    @Override
    public void doCreate(Bundle savedInstanceState) {
        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        bookAliWechat.setText("支付宝账单", "微信账单");

    }

    @Override
    public void initEvent() {
        titleView.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        bookAliWechat.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                LogUtils.d("bookAliWechat position=" + position);
                if (position == 0) {
                    bookType = 1;
                } else if (position == 1) {
                    bookType = 2;
                }
            }
        });

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void showError(int code, String msg) {
        bookCsvPath.setText(msg);
        fileCSV = null;
        dialog.dismiss();
        super.showError(code, msg);
    }

    @Override
    public void onSuccess(String msg) {
        bookCsvPath.setText(msg);
        fileCSV = null;
        dialog.dismiss();
        showMessage(msg);
        EventBusUtil.sendEvent(new Event(C.EventCode.REFRESH_HOME));
    }

    @OnClick({R.id.book_import, R.id.book_csv_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.book_csv_add:
                openFile();
                break;
            case R.id.book_import:
                if (Utils.isFastClick(view, 3200)) {
                    mPresenter.bookImport(AppUserHelper.getInstance().getUser().getUserUseBook(),
                            bookType, AppUserHelper.getInstance().getUser().getUserId(),
                            fileCSV, mProgressDialog, listener);
                }
                break;
        }
    }

    String rootPath = "";  //外置 SD 卡路径

    private void openFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //任意类型文件
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, OPEN_DOCUMENT_FILE_CODE);
    }

    private void openFileRootPath() {
        rootPath = DocumentsUtils.getStoragePath(this, true);  //获取 可以插拔的 sd 卡  路径
        LogUtils.i("openFileRootPath=" + DocumentsUtils.getTree(this, rootPath));
        LogUtils.i("openFileRootPath=" + rootPath);
        if (!DocumentsUtils.getTree(this, rootPath)) {
            Intent i = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            }
            startActivityForResult(i, DocumentsUtils.OPEN_DOCUMENT_TREE_CODE);
        } else {
            File newFile = new File(newPath);
            if (DocumentsUtils.renameTo(CSVImportActivity.this, fileSave, newFile)) {
                LogUtils.i("openFileRootPath OPEN_DOCUMENT_TREE_CODE=" + newFile.getAbsolutePath());
                fileCSV = newFile;
                bookCsvPath.setText(newFile.getName());
            } else {
                ToastUtils.show("外置SD内存操作重命名失败，因上传文件名不能为中文，否则无法上传解析，请重新选择文件处理！");
            }

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data != null && data.getData() != null) {
            switch (requestCode) {
                case DocumentsUtils.OPEN_DOCUMENT_TREE_CODE:
                    Uri uri = data.getData();
                    DocumentsUtils.saveTreeUri(this, rootPath, uri);

                    File newFile = new File(newPath);
                    if (DocumentsUtils.renameTo(CSVImportActivity.this, fileSave, newFile)) {
                        LogUtils.i("OPEN_DOCUMENT_TREE_CODE=" + newFile.getAbsolutePath());
                        fileCSV = newFile;
                        bookCsvPath.setText(newFile.getName());
                    } else {
                        ToastUtils.show("外置SD内存操作重命名失败，因上传文件名不能为中文，否则无法上传解析，请重新选择文件处理！");
                    }
                    break;
                case OPEN_DOCUMENT_FILE_CODE:
                    LogUtils.d("openFile uri=" + data.getData());
                    Uri pathUri = data.getData();
                    LogUtils.d("openFile pathUri=" + pathUri.getPath());
                    LogUtils.d("openFile2 uri=" + FileUtils.getPath2uri(CSVImportActivity.this, data.getData()));

                    String filePath = FileUtils.getPath2uri(CSVImportActivity.this, data.getData());
                    if (StringUtils.isNotBlank(filePath)) {
                        fileSave = new File(filePath);
                        if (fileSave.getName().contains("微信")) {
                            String name;
                            String[] newName = fileSave.getName().split("\\(");
                            if (newName.length > 1) {
                                name = "wechat" + newName[1];
                                String[] strings = name.split("\\)");
                                name = strings[0] + strings[1];
                                name = name.replace("-", "_");
                                LogUtils.d("openFile name=" + name);

                                LogUtils.d("openFile DocumentsUtils=" + DocumentsUtils.isOnExtSdCard(fileSave, CSVImportActivity.this));
//                                newPath = filePath.replace(fileSave.getName(), name);//将文件名替换
//                                if (DocumentsUtils.isOnExtSdCard(fileSave, CSVImportActivity.this)) {
//                                    openFileRootPath();
//                                } else {
                                File newFiles = FileUtils.chageFileName(fileSave.getAbsolutePath(), name);
                                if (newFiles != null) {
                                    fileCSV = newFiles;
                                    bookCsvPath.setText(newFiles.getName());
                                } else {
                                    ToastUtils.show("重命名失败，因上传文件名不能为中文，否则无法上传解析，请手动修改文件名后上传！");
                                }
//                                }
                            }
                        } else {
                            fileCSV = fileSave;
                            bookCsvPath.setText(fileSave.getName());
                        }

                    }

                    break;
            }
        }


    }
}
